package ug.co.icom.kyazze.healthticket.services;

import java.io.File;

import cpabe.Cpabe;
import ug.co.icom.kyazze.healthticket.mongoHQ.UploadToServer;
import android.app.IntentService;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;

public class IntentServiceOnCreateMain extends IntentService{
	private final static String TAG="IntentServiceOnCreateMain";
	File directory;
	private String filepath = "healthTicket_files";
	
	static String student_attr = "objectClass:inetOrgPerson objectClass:organizationalPerson "
			+ "sn:student2 cn:student2 uid:student2 userPassword:student2 "
			+ "ou:idp o:computer mail:student2@sdu.edu.cn title:student";

	static String student_policy = "sn:student2 cn:student2 uid:student2 3of3";
	static String[] attr = { "baf1", "fim1", "foo" };
	static String policy = "foo bar fim 2of3 baf 1of2";

	public IntentServiceOnCreateMain() {
		super(TAG);

	}

	@Override
	protected void onHandleIntent(Intent intent) {
		
		ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
		directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
		
		@SuppressWarnings("unused")
		SharedPreferences prefs = getSharedPreferences("ULS", 0);	
		
		ApplicationObject mApplication = (ApplicationObject)getApplicationContext();
		long PhoneNumber = mApplication.getphone_number();
		
		//
		String attr_str;
		String inputfile = directory+"/"+PhoneNumber+".txt";
		String pubfile = directory+"/"+PhoneNumber+"pub_key";
		String mskfile = directory+"/"+PhoneNumber+"master_key";
		String encfile = directory+"/"+PhoneNumber+".cpabe";
		String prvfile = directory+"/"+PhoneNumber+"prv_key";
		

		attr_str = student_attr;
		policy = student_policy;
		
		Cpabe test = new Cpabe();
		try {
			test.setup(pubfile, mskfile);
			//keygen here
			test.enc(pubfile, policy, inputfile, encfile);			
			//generate private key
			test.keygen(pubfile, prvfile, mskfile, attr_str);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	 // upload key files
		 UploadToServer file_upload = new UploadToServer();
		 file_upload.execute(PhoneNumber,directory);
	}

}
